/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tags;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import javax.servlet.http.HttpServletRequest;


/**
 *
 * @author admin
 */
public class CounterTag extends TagSupport{
    
    private int count=0;
    private File file=null;
    
    public int doStartTag() throws JspException{
        try{
            checkFile();
            readCount();
            pageContext.getOut().print(++count);
        }catch(java.io.IOException ex){
            throw new JspException(ex.getMessage());
        }
        return SKIP_BODY;
    }
    
    public int doEndTag() throws JspException {
        saveCount();
        return EVAL_PAGE; 
    }

    private void checkFile() throws IOException, JspException {
        if(file==null){
            file = new File(getCounterFilename());
            count=0;
        }
        
        if(!file.exists()){
        file.createNewFile();
        saveCount();
        }
    }

     private String getCounterFilename() {
        HttpServletRequest req = (HttpServletRequest)pageContext.getRequest();
        String servletPath = req.getServletPath();
        String realPath = pageContext.getServletContext().getRealPath(servletPath);
        return realPath + ".couner";
        
    }
    
    private void saveCount() throws JspException {
        try{
            FileWriter writer= new FileWriter(file);
            writer.write(count);
            writer.close();
            
        }catch(Exception ex){
         throw new JspException(ex.getMessage());
        }
    }

    private void readCount() throws JspException {
        try {
            FileReader reader = new FileReader(file);
            count = reader.read();
            reader.close();
            
        }catch(Exception ex){
         throw new JspException(ex.getMessage());
        }
            
    }
    
}
